from django.conf import settings
from django.core.urlresolvers import reverse

from application_flow.models import ServerApplication, Approval
from . import demail


def get_boss_approver_info(approvers=settings.APPROVERS):
    approver_orig_data = dict(approvers)
    approver_data = {}
    for email, name_str in approver_orig_data.items():
        names = name_str.split(',')
        name = names[0]
        respectful_name = ''
        if len(names) == 2:
            respectful_name = names[1]

        approver_data[email] = {
            'name': name,
            'respectful_name': respectful_name
        }

    return approver_data


# generate the latest approval message
def get_approval_text(application):
    text = "审批完成"
    for approval in application.approval_set.all():
        if approval.result is None:
            text = "等待 %s 审批" % (approval.approver_name)
            break

        if approval.result is False:
            text = "已被 %s 驳回" % (approval.approver_name)
            break

    return text


# get the next approver who hasn't approved yet
# return None if no any approver is matched
def get_next_approval(application):
    approvals = application.approval_set.filter(result=None)
    if len(approvals) > 0:
        approval = approvals[0]
        return approval
    else:
        return None


# get the last approver who has already approved
# return None if no any approver is matched
def get_last_approval(application):
    approvals = application.approval_set.all()
    for approval in approvals:
        if approval.result is not None:
            return approval

    return None


def gen_approval_email_content(application, approval):
    receiver = approval.approver_respectful_name
    if not receiver:
        receiver = approval.approver_name

    path = reverse('application:approval', kwargs={'app_id': application.id})
    url = '%s%s' % (settings.SERVER_URL, path)
    d = {
        'receiver': receiver,
        'applicant': application.user_name,
        'url': url,
    }
    content = settings.NEXT_APPROVAL_EMAIL_TEMPLATE.format(**d)
    return content


def gen_reject_email_content(application, approval):
    approver = approval.approver_respectful_name
    if not approver:
        approver = approval.approver_name

    path = reverse('application:detail', kwargs={'app_id': application.id})
    url = '%s%s' % (settings.SERVER_URL, path)
    d = {
        'receiver': application.user_name,
        'approver': approver,
        'url': url,
    }
    content = settings.REJECT_EMAIL_TEMPLATE.format(**d)
    return content


def gen_agree_email_content(application, approval):
    approver = approval.approver_respectful_name
    if not approver:
        approver = approval.approver_name

    path = reverse('application:detail', kwargs={'app_id': application.id})
    url = '%s%s' % (settings.SERVER_URL, path)
    d = {
        'receiver': application.user_name,
        'approver': approver,
        'url': url,
    }
    content = settings.AGREE_EMAIL_TEMPLATE.format(**d)
    return content


def gen_pass_email_content(application):
    path = reverse('application:detail', kwargs={'app_id': application.id})
    url = '%s%s' % (settings.SERVER_URL, path)
    d = {
        'receiver': application.user_name,
        'url': url,
    }
    content = settings.PASS_EMAIL_TEMPLATE.format(**d)
    return content


# send approval remind email
def send_email_to_next_approval(application):
    approval = get_next_approval(application)
    if approval is None:
        # maybe it is at the ending of all approvals
        return

    content = gen_approval_email_content(application, approval)
    send_email(approval.approver_email, content, subject='服务器资源申请(审批)')


def send_pass_email_to_applicant(application):
    content = gen_pass_email_content(application)
    send_email(application.user_email, content, subject='服务器资源申请(完成)')


def send_reject_email_to_applicant(application):
    approval = get_last_approval(application)
    if approval is None:
        raise Exception('审批者未找到，这似乎是一个bug -.-|，请与开发人员联系。')

    content = gen_reject_email_content(application, approval)
    send_email(application.user_email, content, subject='服务器资源申请(驳回)')


def send_agree_email_to_applicant(application):
    approval = get_last_approval(application)
    if approval is None:
        raise Exception('审批者未找到，这似乎是一个bug -.-|，请与开发人员联系。')

    content = gen_agree_email_content(application, approval)
    send_email(approval.approver_email, content, subject='服务器资源申请(通过)')


def send_email(email, content, cc=[], subject='服务器资源申请'):
    default_cc = settings.EMAIL.get('default_cc')
    if default_cc:
        cc += default_cc

    e = demail.Email()
    e.send(email, subject, content, CC=cc, auto_close=True)
